<template>
  <view class="custom-upload flex">
    <view class="file-list gap-1 flex-items-center">
      <view v-for="(file, index) in fileList" :key="index" class="file-item">
        <view v-if="isImage(file.fileName)">
          <view :class="file.isAnomaly ? 'warning-wrapper' : ''">
            <image
              class="w18vw h18vw bg-#f5f5f5 flex justify-center flex-items-center"
              :src="file.fileId"
              @click="controls(file, index)"
              mode="aspectFit"
            />
          </view>
        </view>
        <view v-else-if="isPDF(file.fileName)">
          <view class="w18vw h18vw bg-#f5f5f5 flex justify-center flex-items-center" @click="controls(file, index)">
            预览 {{ file.fileSuffix }}
          </view>
        </view>
        <view v-else-if="isVideo(file.fileName)">
          <view class="w18vw h18vw bg-#f5f5f5 flex justify-center flex-items-center" @click="controls(file, index)">
            <wd-icon name="play-circle" size="22px"></wd-icon>
          </view>
        </view>
        <view v-else>
          <view class="w18vw h18vw bg-#f5f5f5 flex justify-center flex-items-center" @click="controls(file, index)">
            下载文件
          </view>
        </view>
      </view>
      <view class="w18vw h18vw bg-#f5f5f5 flex justify-center flex-items-center" @click="handleClick">
        <wd-icon name="camera" color="#b8b8b8" size="22px"></wd-icon>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits } from 'vue'
import { upload } from '@/utils/qiniuUploader'
import http from '@/http/httpClient'
const props = defineProps<{
  modelValue: any[]
  accept: 'image' | 'video' | 'all' | 'file'
}>()

const emit = defineEmits(['update:modelValue'])

watch(
  () => props.modelValue,
  newVal => {
    fileList.value = newVal
  },
  { deep: true }
)

const fileList = ref(props.modelValue || [])

const controls = (file, index) => {
  if (isImage(file.fileName)) {
    uni.showActionSheet({
      itemList: ['预览', '整改', '删除'],
      success: res => {
        if (res.tapIndex === 0) {
          previewImage(file.fileId)
        } else if (res.tapIndex === 1) {
          fileList.value[index].isAnomaly = true
        } else if (res.tapIndex === 2) {
          fileList.value.splice(index, 1)
        }
      },
      fail: err => {
        console.error('显示操作菜单失败', err)
      }
    })
  } else if (isPDF(file.fileName)) {
    preview(file.fileId)
  } else if (isVideo(file.fileName)) {
    previewVideo(file.fileId)
  } else {
    downloadFile(file)
  }
}
// 聊天记录选择
const chooseMessageFile = () => {
  wx.chooseMessageFile({
    count: 20,
    type: props.accept || 'all',
    success: res => {
      uploadFiles(res.tempFiles)
    },
    fail: err => {
      console.error('选择文件失败', err)
    }
  })
}

// 拍照
const cameraImage = () => {
  wx.chooseMedia({
    count: 1,
    mediaType: ['image', 'video'],
    sourceType: ['camera'],
    camera: 'back',
    success: res => {
      console.log(res, 56555)

      uploadFiles(res.tempFiles)
    }
  })
}
// 相册选择
const albumImage = () => {
  wx.chooseMedia({
    count: 6, // 最多选择数量
    mediaType: ['image', 'video'],
    sourceType: ['album'], // 来源：相册或相机
    success(res) {
      const tempFiles = res.tempFiles // 临时文件路径
      uploadFiles(tempFiles)
    }
  })
}

const uploadFiles = async files => {
  uni.showLoading({
    title: '上传中...',
    mask: true
  })
  const tokenRes: any = await http.get('/api/file/getToken')
  const token = tokenRes.data

  const uploadPromises = files.map(file => {
    return new Promise((resolve, reject) => {
      upload({
        filePath: file.path || file.tempFilePath,
        options: {
          uptoken: token,
          uptokenFunc: () => token,
          shouldUseQiniuFileName: true
        },
        before: () => {
          console.log('before upload')
        },
        success: res => {
          resolve({
            fileId: 'https://file.coolthinker.cn/' + res.hash,
            fileName: file.name || res.hash + '.' + getFileExtension(file.path || file.tempFilePath),
            fileSuffix: getFileExtension(file.path || file.tempFilePath)
          })
        },
        fail: err => {
          reject(err)
        }
      })
    })
  })

  try {
    const uploadedFiles = await Promise.all(uploadPromises)
    fileList.value = [...fileList.value, ...uploadedFiles]
    uni.hideLoading()
    emit('update:modelValue', fileList.value)
  } catch (error) {
    console.error('文件上传失败', error)
  }
}

function getFileExtension(url) {
  // 使用正则表达式或简单的字符串操作来获取扩展名
  const parts = url.split('.')
  return parts.length > 1 ? parts.pop().toLowerCase() : null
}
function handleClick() {
  uni.showActionSheet({
    itemList: ['拍照', '从相册中选择', '上传文件', '从聊天记录中选择'],
    success: res => {
      if (res.tapIndex === 0) {
        cameraImage()
      } else if (res.tapIndex === 1) {
        albumImage()
      } else {
        chooseMessageFile()
      }
    }
  })
}
// function getFileExtension(url) {
//   // 使用正则表达式或简单的字符串操作来获取扩展名
//   const parts = url.split('.')
//   return parts.length > 1 ? parts.pop().toLowerCase() : null
// }

function isImage(url) {
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp']
  const extension = getFileExtension(url)
  return extension && imageExtensions.includes(extension)
}

function isVideo(url) {
  const videoExtensions = ['mp4', 'mov', 'avi', 'wmv', 'flv', 'mkv']
  const extension = getFileExtension(url)
  return extension && videoExtensions.includes(extension)
}

function isPDF(url) {
  const videoExtensions = ['docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf']
  const extension = getFileExtension(url)
  return extension && videoExtensions.includes(extension)
}

function isOtherType(url) {
  // 如果不是图片也不是PDF，则认为是其他类型
  const extension = getFileExtension(url)
  return extension && !isImage(url) && !isPDF(url)
}

function previewImage(url) {
  const urls = fileList.value.map(v => v.fileId) // 直接获取一维数组
  wx.previewImage({
    current: url, // 当前图片的 URL
    urls: urls as string[] // 确保类型为 string[]
  })
}

function previewVideo(url) {
  uni.navigateTo({
    url: '/pages/ticket/lookVideo?url=' + url
  })
}

function preview(url) {
  // 下载文件到临时路径
  wx.downloadFile({
    url: url,
    success: res => {
      if (res.statusCode === 200) {
        console.log(res, 666)

        // 预览 PDF
        wx.openDocument({
          filePath: res.tempFilePath,
          success: () => console.log('预览成功'),
          fail: err => console.error('预览失败', err)
        })
      }
    },
    fail: err => console.error('下载失败', err)
  })
}

function downloadFile(file) {
  wx.downloadFile({
    url: file.fileId,
    success: function (res) {
      const filePath = res.tempFilePath
      wx.saveFile({
        tempFilePath: filePath,
        success: function (res) {
          const savedFilePath = res.savedFilePath
          console.log('文件保存成功', savedFilePath)
        },
        fail: function (err) {
          console.error('文件保存失败', err)
        }
      })
    },
    fail: function (err) {
      console.error('下载文件失败', err)
    }
  })
}
</script>

<style scoped lang="scss">
.warning-wrapper {
  position: relative;
  padding: 6rpx;
  border-radius: 12rpx;
  background: linear-gradient(
    45deg,
    rgba(255, 59, 48, 0.1) 0%,
    rgba(255, 59, 48, 0.2) 74%,
    rgba(255, 59, 48, 0.1) 100%
  );

  &::after {
    content: '';
    position: absolute;
    top: -4rpx;
    left: -4rpx;
    right: -4rpx;
    bottom: -4rpx;
    border: 2rpx solid rgba(255, 59, 48, 0.3);
    border-radius: 16rpx;
    pointer-events: none;
  }
}
.custom-upload {
  .upload-button {
    margin-bottom: 10px;
  }

  .file-list {
    display: flex;
    flex-wrap: wrap;

    .file-item {
      margin: 5px;
      position: relative;

      .preview-image {
        width: 80px;
        height: 80px;
        object-fit: cover;
      }

      .preview-pdf,
      .download-file {
        width: 80px;
        height: 80px;
        padding: 10px;
        background-color: #f0f0f0;
        border-radius: 5px;
        text-align: center;
        cursor: pointer;
      }
    }
  }
}
</style>
